<template>
  <div class="dashboard-container">
    <div class="app-container">
      <div class="edit-form">
        <el-form ref="userForm" :model="formData" :rules="rules" label-width="220px">
          <!-- 姓名 部门 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="username">
                <el-input v-model="formData.username" size="mini" class="inputW" />
              </el-form-item>
            </el-col>

          </el-row>
          <!-- 工号 入职时间 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="工号" prop="workNumber">
                <el-input v-model="formData.workNumber" disabled size="mini" class="inputW" />
              </el-form-item>
            </el-col>
          </el-row>
          <!--手机 聘用形式  -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机" prop="mobile">
                <el-input
                  v-model="formData.mobile"
                  :disabled="formData.id?true:false"
                  size="mini"
                  class="inputW"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门" prop="departmentId">
                <!-- 放置及联部门组件
                    options: 级联数据
                    label：指定渲染内容的属性名
                    value：指定和v-model绑定的变量双向绑定的属性名
                    :props="{label: 'name',value: 'id',emitPath: false}"
                    emitPath: false: 值获取最后一级的值
                 -->
                <el-cascader
                  v-model="checkDeptsId"
                  style="width:300px"
                  :options="depts"
                  :props="{label: 'name',value: 'id'}"
                  @change="changeDept"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="聘用形式" prop="formOfEmployment">
                <el-select v-model="formData.formOfEmployment" size="mini" class="inputW">
                  <el-option
                    v-for="item in employmentList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="入职时间" prop="timeOfEntry">
                <el-date-picker
                  v-model="formData.timeOfEntry"
                  size="mini"
                  type="date"
                  value-format="yyyy-MM-dd"
                  class="inputW"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="转正时间" prop="correctionTime">
                <el-date-picker
                  v-model="formData.correctionTime"
                  size="mini"
                  type="date"
                  class="inputW"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 员工照片 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="员工头像">
                <!-- 放置上传图片 -->
                <ImgUpload v-model="formData.staffPhoto" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 保存个人信息 -->
          <el-row type="flex">
            <el-col :span="12" style="margin-left:220px">
              <el-button size="mini" type="primary" @click="submit">保存更新</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

    </div>
  </div>
</template>

<script>
import { departmentList } from '@/api/department'
import { transListToTreeData } from '@/utils'
import { addEmployee, employeeDetails, updateEmployee } from '@/api/employee'
import ImgUpload from './components/img-upload'
export default {
  components: { ImgUpload },
  data() {
    return {
      employmentList: [
        {
          label: '正式',
          value: 1
        }, {
          label: '非正式',
          value: 2
        }
      ],
      depts: [],
      deptList: [],
      checkDeptsId: [],
      formData: {
        staffPhoto: '', // 员工头像
        username: '', // 用户名
        mobile: '', // 手机号
        workNumber: '', // 工号
        formOfEmployment: null, // 聘用形式
        departmentId: null, // 部门id
        timeOfEntry: '', // 入职时间
        correctionTime: '' // 转正时间
      },
      rules: {
        username: [{ required: true, message: '请输入姓名', trigger: 'blur' }, {
          min: 1, max: 4, message: '姓名为1-4位'
        }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }, {
        //   pattern 正则表达式
          pattern: /^1[3-9]\d{9}$/,
          message: '手机号格式不正确',
          trigger: 'blur'
        }],
        formOfEmployment: [{ required: true, message: '请选择聘用形式', trigger: 'blur' }],
        departmentId: [{ required: true, validator: (rule, value, callback) => {
          if (this.checkDeptsId.length === 0) {
            callback('请选择部门')
          } else {
            callback()
          }
        }, trigger: 'blur' }],
        timeOfEntry: [{ required: true, message: '请选择入职时间', trigger: 'blur' }],
        correctionTime: [{ required: true, message: '请选择转正时间', trigger: 'blur' }, {
          validator: (rule, value, callback) => {
            if (this.formData.timeOfEntry) {
              if (new Date(this.formData.timeOfEntry) > new Date(value)) {
                callback(new Error('转正时间不能小于入职时间'))
                return
              }
            }
            callback()
          }
        }]
      }

    }
  },
  async created() {
    await this.getDepts()
    if (this.$route.params.id) {
      this.getDetails(this.$route.params.id)
    }
  },
  methods: {
    // 获取员工详情
    async getDetails(id) {
      const res = await employeeDetails(id)
      // 回显
      this.formData = res
      // 部门回显
      // this.checkDeptsId = this.formData.departmentId
      // this.checkDeptsId = [1, 7, 15]
      this.checkDeptsId = this.formData.departmentId
      // this.checkDeptsId = [] // 这行代码必须加上才能实现部门的回显
      // this.getFullId(this.formData.departmentId)
    },
    // 找父id
    getFullId(id) {
      this.deptList.forEach(item => {
        if (item.id === id) {
          this.checkDeptsId.unshift(id)
          this.getFullId(item.pid)
        }
      })
    },
    // 获取部门列表
    async getDepts() {
      this.deptList = await departmentList()
      this.depts = transListToTreeData(this.deptList, 0)
    },
    // 选择部门
    changeDept() {
      if (!this.checkDeptsId) { return }
      const id = this.checkDeptsId[this.checkDeptsId.length - 1]
      this.formData.departmentId = id
      // this.formData.departmentId = this.checkDeptsId
    },
    async submit() {
      await this.$refs.userForm.validate()
      console.log('校验通过')
      if (this.formData.id) {
        await updateEmployee(this.formData)
        this.$message.success('修改员工成功！')
      } else {
        await addEmployee(this.formData)
        this.$message.success('新增员工成功！')
      }
      this.$router.push('/employee')
    }
  }
}
</script>

<style scoped lang="scss">
    .edit-form {
      background: #fff;
      padding: 20px;
      .inputW {
        width: 380px
      }
    }

</style>
